package com.yueya.auth.realm;

import com.yueya.auth.token.JwtToken;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authc.credential.AllowAllCredentialsMatcher;
import org.apache.shiro.authc.credential.HashedCredentialsMatcher;

import static com.yueya.auth.utils.CredentialsHelper.HASH_ALGORITHM;
import static com.yueya.auth.utils.CredentialsHelper.HASH_INTERATIONS;

public class AccountRealm extends PmsRealm{
    private HashedCredentialsMatcher matcher = new HashedCredentialsMatcher(HASH_ALGORITHM);
    public AccountRealm(){
    }
    @Override
    public boolean supports(AuthenticationToken token) {
        return token instanceof JwtToken || token instanceof UsernamePasswordToken;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        if (token instanceof JwtToken){
            return getJwtAuthenticationInfo(token);
        }else {
            return getFormAuthenticationInfo(token);
        }
    }


    /**
     * 设定密码校验的Hash算法与迭代次数
     */
    public void setCredentialsMatcher() {
        matcher.setHashIterations(HASH_INTERATIONS);
        setCredentialsMatcher(matcher);
    }

    /**
     * 重写判断密码是否下相等方法，否则直接从缓存获取用户信息时，登录验证会报错
     * @param token
     * @param info
     * @throws AuthenticationException
     */
    @Override
    protected void assertCredentialsMatch(AuthenticationToken token, AuthenticationInfo info) throws AuthenticationException {
        if (token instanceof JwtToken){
            setNoCredentialsMatcher();
        }else {
            setCredentialsMatcher();
        }
        super.assertCredentialsMatch(token, info);
    }

    public void setNoCredentialsMatcher() {
        setCredentialsMatcher(new AllowAllCredentialsMatcher());
    }
    /*@Override
    public void onAuthInfoChange(Account account, Set<String> roles, Set<String> permissions) {
        Principal principal = new Principal(account.getId(),account.getAccount(),roles,permissions);
        clearCachedAuthenticationInfo(new SimplePrincipalCollection(principal, getName()));
        clearCachedAuthorizationInfo(new SimplePrincipalCollection(principal, getName()));
    }

    @Override
    public void clearUserCache() {
        String authenicationKey = getAuthenticationCacheName();
        String authorizationKey = getAuthorizationCacheName();
        getCacheManager().getCache(authenicationKey).clear();
        getCacheManager().getCache(authorizationKey).clear();
    }*/

}
